import { Editor,Element,Transforms,Range,Text } from "slate"
import { useSlate } from "slate-react"

export const withInlines =  (editor:any) => {
    const { isInline } = editor
    
    editor.isInline = (element:any) =>
      ['image','link', 'button', 'badge'].includes(element?.type) || isInline(element)
  
   
    return editor
  }

export default ()=>{
  const editor = useSlate();

  const isLinkActive = () => {
    const [link] = Editor.nodes(editor, {
      match: n =>
        !Editor.isEditor(n) && Element.isElement(n) && n.type === 'link',
    })
    return !!link
  }

  const wrapLink=(url:string)=>{

    if(!editor?.selection||!url){
      return;
    }
    
    if(isLinkActive()){
     alert("+++++")
    //  Transforms.unwrapNodes(editor, {
    //    match: n =>
    //      !Editor.isEditor(n) && Element.isElement(n) && n?.type === 'link',
    //  })
     return;
    }
   
    const {selection} = editor;  

    const isCollapsed = selection && Range.isCollapsed(selection)

    const link= { type: 'link', url:url,children: isCollapsed ? [{ text: url }] : []}
     if(isCollapsed){
       Transforms.insertNodes(editor, link)
 
     }else{
 
       Transforms.wrapNodes(  
         editor,  
         link,
         { split: true }  
       );
       Transforms.collapse(editor, { edge: 'end' })
 
     }
   
 }
  return {
    wrapLink
  }
}